from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String, PrimaryKeyConstraint, DateTime, func, Float

Base = declarative_base()


# 定义一个用户类
class Trade(Base):
    __tablename__ = 'my_trade'

    code = Column(String(30), comment="股票代码")
    date = Column(String(20), comment="交易日期")
    strategy = Column(String(50), comment="策略名称")
    price = Column(Float, default=0, comment="策略价")
    deal_price = Column(Float, default=0, comment="成交价")
    amount = Column(Integer, default=0, comment="成交量,正数为买入，负数为卖出")
    execute = Column(Integer, default=0, comment="0:未成交，1:已成交")
    trade_info = Column(String(200), comment="交易信息")
    create_time = Column(DateTime, default=func.now(), nullable=False, comment="创建时间")

    # 指定主键约束
    __table_args__ = (
        PrimaryKeyConstraint('date', 'code', 'strategy'),  # 声明复合主键
    )

    # __repr__ 用于易读性和调试
    def __repr__(self):
        return f"\nUser(code={self.code}, date={self.date}, amount={self.amount})"


# 持仓表
class Position(Base):
    __tablename__ = 'my_position'
    code = Column(String(30), comment="股票代码", primary_key=True)
    amount = Column(Integer, default=0, comment="持仓量")


class MyNotSuggest(Base):
    __tablename__ = 'my_not_suggest'
    code = Column(String(30), comment="股票代码", primary_key=True)
    expire_date = Column(String(20), comment="过期日期")
    reason = Column(String(200), comment="原因")
    strategy = Column(String(50), comment="策略")
    create_time = Column(DateTime, default=func.now(), nullable=False, comment="创建时间")


class MySignals(Base):
    __tablename__ = 'my_signals'
    code = Column(String(15), comment="股票代码")
    stg = Column(String(100), comment="策略名称")
    param = Column(String(500), comment="参数")
    detail = Column(String(200), comment="信号详情")
    sid = Column(String(32), comment="运行id")
    profit_rate = Column(Float, comment="收益率")
    __table_args__ = (
        PrimaryKeyConstraint('code', 'param'),  # 声明复合主键
    )

    def __repr__(self):
        return f"信号数据: MySignals(code={self.code}, stg={self.stg}, param={self.param}, detail={self.detail})"


class MyResult(Base):
    __tablename__ = 'my_result'
    sid = Column(String(50), comment="策略运行结果id")
    profit_rate = Column(Float, comment="收益率")
    input = Column(Float, comment="投入本金")
    output = Column(Float, comment="市值")
    trader = Column(String(30), comment="交易类型")
    stg = Column(String(50), comment="策略")
    __table_args__ = (
        PrimaryKeyConstraint('sid', 'trader'),  # 声明复合主键
    )

    def __repr__(self):
        return f"盈利数据: MyResult(sid={self.sid}, profit_rate={self.profit_rate})"


# 创建表
if __name__ == '__main__':
    from tools.dbTool import dbTool

    Base.metadata.create_all(dbTool.getEngine())
    # DBTool.save(Trade(code='000003', date='2022-01-01', strategy='test2', price=1, amount=2))
    dbTool.save(Position(code='000001', amount=500))
